package cn.t.facade.device;


import cn.t.constants.device.HeartbeatTypeEnum;
import cn.t.converter.device.DeviceHeartbeatDTOConverter;
import cn.t.core.exception.BizException;
import cn.t.core.facade.FacadeImpl;
import cn.t.core.mode.YesNoEnum;
import cn.t.dto.android.DeviceHeartbeatDTO;
import cn.t.core.enums.base.BaseStatusEnum;
import cn.t.core.enums.base.CommonError;
import cn.t.model.device.DeviceDO;
import cn.t.model.device.DeviceHeartbeatDO;
import cn.t.runtime.dto.HeartBeatRequest;
import cn.t.service.device.DeviceHeartbeatService;
import cn.t.service.device.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 * @author l
 */
@Slf4j
@Component
public class HeartbeatFacade extends FacadeImpl<DeviceHeartbeatDTO, DeviceHeartbeatDO, DeviceHeartbeatDTOConverter, DeviceHeartbeatService> {

    public DeviceHeartbeatDO isValidate(String imei, String token) {

        DeviceHeartbeatDO previous = service.isValidateToken(imei, token);

        if (previous == null) {
            String errorMessage = String.format("心跳验证异常 imei=%s previous=%s", imei, token);
            log.error(errorMessage);
            throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
        }

        return previous;
    }


    public DeviceHeartbeatDTO heartbeat(HeartBeatRequest request) {

        DeviceHeartbeatDO previous = isValidate(request.getImei(), request.getPreviousToken());

        if (previous.getGmtCreated() != null) {
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(previous.getGmtCreated());
            calendar.add(Calendar.HOUR, 2);
            if (now.before(calendar.getTime())) {
                service.refreshToken(previous);

                return converter.model2Dto(previous);
            }
        }

        DeviceDO device = deviceService.getDeviceByImei(request.getImei());

        DeviceHeartbeatDO newHeartbeat = new DeviceHeartbeatDO();
        newHeartbeat.setImei(request.getImei());
        newHeartbeat.setDeviceId(device.getId());
        newHeartbeat.setPin(previous.getPin());
        newHeartbeat.setStatus(String.valueOf(BaseStatusEnum.AVAILABLE.getCode()));
        newHeartbeat.setIsDeleted(YesNoEnum.FALSE);
        newHeartbeat.setType(String.valueOf(HeartbeatTypeEnum.HTTP.getCode()));
        newHeartbeat.setRefreshTimes(0);
        service.save(newHeartbeat);

        return converter.model2Dto(newHeartbeat);

    }


    @Autowired
    private DeviceService deviceService;
}
